<script setup lang="ts">
import { getCurrentInstance, reactive, ref } from "vue";
import { reqAuthUserSelectAllUrl, reqRoleAuthUserUnAllocatedListUrl } from "@/api/system/role";
import { ElMessage, ElTable, FormInstance } from "element-plus";
import { reqAddUserInGroupUrl, reqUnAllocatedListUrl } from "@/api/gather/group";
import Group from "@/views/system/group/index.vue";
import DictTag from "@/components/DictTags/index.vue";

/*获取父组件传递来的信息*/
const props = defineProps({
  roleId: {
    type: Number,
    required: true
  }
});

let $emit = defineEmits(["ok"]);
const { proxy }: any = getCurrentInstance();
const userList = ref([]);
const total = ref(0);
const queryFormRef = ref<FormInstance>(); /*查询表单的Ref*/
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  username: "",
  phonenumber: ""
});
const dialogVisible = ref(false); /*对话框框开关*/
const table = ref<InstanceType<typeof ElTable>>();
const userIds = ref([]); // 选中数组值
const userGroup = ref([]); // 选中数组值
const groupId = ref(); // 分组id

const initFormData = (item) => {
  dialogVisible.value = true;
  groupId.value = item.groupId;
  getUnList();
};

/*进行查询*/
const handleQuery = async () => {
  if(userGroup.value.length > 0) {
    table.value.clearSelection(); // 清理被选中的行
  }
  queryParams.pageNum = 1;
  await getUnList();
};
// 重置表单
const resetQuery = () => {
  queryFormRef.value.resetFields();
  Object.keys(queryParams).forEach((key) => {
    if (key === "pageNum") {
      queryParams[key] = 1;
    } else if (key === "pageSize") {
      queryParams[key] = 10;
    } else {
      queryParams[key] = "";
    }
  });
  handleQuery();
};

// 获取未授予该角色权限的用户
const getUnList = async () => {
  // 获取未被选中的user
  await reqUnAllocatedListUrl(groupId.value, queryParams)
    .then((req) => {
      if (req.code === 200) {
        userList.value = req.rows;
        total.value = req.total;
      }else {
        proxy.$modal.msgError(req.message !== null ? req.message : "未查询到任何信息!");
      }
    })
    .catch((e) => {});
};

/*当点击行时，进行选中操作*/
const clickRow = (row: any, column, event) => {
  const findIndex = userIds.value.indexOf(row.userId);
  if (findIndex == -1) {
    /*userIds中没有userId*/
    table.value.toggleRowSelection(row, true);
  } else {
    /*说明已经存在了进行移除*/
    table.value.toggleRowSelection(row, false);
  }
};

/*多选框选中数据*/
interface userGroup {
  groupId: number,
  userId: number,
  type: string,
}
const handleSelectionChange = (selection: any) => {
  userIds.value = selection.map((item: any) => item.userId); /*将多选框选中后的数据放到userIds中*/
  userGroup.value = selection.map((item: any) => ({groupId: groupId.value, userId: item.userId, type: undefined})); /*将多选框选中后的数据放到userIds中*/
};

/*提交按钮*/
const handleSelectUser = async () => {
  const user_Ids = userIds.value.join(",");
  /*如果没有选中*/
  if (user_Ids == "" || user_Ids == null) {
    proxy.$modal.msgError("请选择要添加的成员！");
    return;
  }
  /*进行添加操作*/
  await reqAddUserInGroupUrl(groupId.value, userGroup.value).then((res) => {
    if (res.code === 200) {
      /*添加成功*/
      proxy.$modal.msgSuccess(res.message);
      dialogVisible.value = false;
      table.value.clearSelection();
      $emit("ok");
    } else {
      proxy.$modal.msgError(res.message);
    }
  });
};

//主动暴露childMethod方法
defineExpose({ initFormData });
</script>

<template>
  <el-dialog title="选择用户" v-model="dialogVisible" width="80%" top="5vh" append-to-body>
    <el-form :model="queryParams" ref="queryFormRef" size="default" :inline="true">
      <el-form-item label="用户名称" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入用户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" size="default" @click="handleQuery">
          搜索
        </el-button>
        <el-button icon="Refresh" size="default" @click="resetQuery"> 重置</el-button>
      </el-form-item>
    </el-form>

    <el-row>
      <el-table
        @row-click="clickRow"
        ref="table"
        :data="userList"
        row-key="userId"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          key="userId"
          :reserve-selection="true"
        ></el-table-column>
        <el-table-column label="用户名称" prop="username" :show-overflow-tooltip="true" />
        <el-table-column label="用户昵称" prop="nickName" :show-overflow-tooltip="true" />
        <el-table-column label="邮箱" prop="email" :show-overflow-tooltip="true" />
        <el-table-column label="手机" prop="phonenumber" :show-overflow-tooltip="true" />
        <el-table-column label="性别" align="center" prop="sex">
          <template v-slot="scope">
            <DictTag
              :options="dict.type.sys_user_sex"
              :value="scope.row.sex"
            ></DictTag>
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          width="180"
        ></el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          v-show="total > 0"
          background
          :page-sizes="[5, 10, 15, 20, 25, 30]"
          :background="true"
          layout="prev, pager, next, jumper, ->,  sizes, total"
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          @current-change="getUnList"
          @size-change="getUnList"
        ></el-pagination>
      </div>
    </el-row>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="success" @click="handleSelectUser">确 定</el-button>
        <el-button type="warning" @click="dialogVisible = false"> 取 消 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
export default {
  dicts: ["sys_user_sex"]
};
</script>

<style scoped lang="scss">
@import "index";

.pagination {
  width: 100%;
  display: flex;
  justify-content: center;
  padding-top: 20px;
  box-sizing: border-box;
}

</style>
